package td.pt;

import java.util.ArrayList;
import java.util.List;

import td.client.place.NameTokens;
import td.client.presenter.RootPresenter;
import td.client.presenter.handlers.DetailUiHandlers;
import td.domain.DemoStore;
import td.domain.Thinker;
import td.domain.Thought;

import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

public class ThinkerPresenter extends
		Presenter<ThinkerPresenter.MyView, ThinkerPresenter.MyProxy> {

	public interface MyView extends View {

		public CellList<Thought> getLatestThoughts();
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.thinker)
	public interface MyProxy extends ProxyPlace<ThinkerPresenter> {
	}

	@Inject
	public ThinkerPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy) {
		super(eventBus, view, proxy);
	}

	@Override
	public void prepareFromRequest(final PlaceRequest request) {
		super.prepareFromRequest(request);
		String name = request.getParameter(DetailUiHandlers.NAME,
				DetailUiHandlers.DEFAULT_NAME);

		Long thinkerId = null;
		try {
			thinkerId = Long.parseLong(name);
		} catch (NumberFormatException nfe) {
			Window.alert("Uknown Thinker ID: " + name);
			return;
		}

		Thinker thinker = DemoStore.db().getThinkersById().get(thinkerId);
		List<Thought> thoughtList = new ArrayList<Thought>(
				thinker.getThoughtsCronologically());

		getView().getLatestThoughts().setRowCount(thoughtList.size(), true);
		getView().getLatestThoughts().setRowData(thoughtList);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, RootPresenter.SLOT_content, this);
	}

	@Override
	protected void onBind() {
		super.onBind();
	}

	@Override
	protected void onReset() {
		super.onReset();
	}
}
